package cricket

import (
	"gorm.io/gorm/clause"
	global2 "longmen/server/config/global"
	"longmen/server/internal/services/nami/utils"
	"longmen/server/pkg/db/mysql/models/models_sports"
)

type InsertUniqueTournamentInterface interface {
	Get() models_sports.CricketUniqueTournament
}

func CrateUniqueTournament(a []InsertUniqueTournamentInterface) {
	records := make([]models_sports.CricketUniqueTournament, 0)
	for _, c := range a {
		records = append(records, c.Get())
	}
	if len(records) == 0 {
		return
	}
	clauses := clause.OnConflict{
		UpdateAll: true,
	}
	err := global2.Sport().Model(records).Clauses(clauses).CreateInBatches(records, 100).Error
	if err != nil {
		return
	}
}

func GetUniqueTournamentTime() int {
	var data models_sports.CricketUniqueTournament
	err := global2.Sport().Model(&data).Order("updated_at DESC").Limit(1).Take(&data).Error
	if err != nil {
		return 0
	}
	return data.UpdatedAt
}

func GetUniqueTournamentId() int {
	var data models_sports.CricketUniqueTournament
	err := global2.Sport().Model(&data).Order("id DESC").Limit(1).Take(&data).Error
	if err != nil {
		return 0
	}
	return data.ID
}

func DeleteUniqueTournament(ids []int) {
	if len(ids) == 0 {
		return
	}
	var model models_sports.CricketUniqueTournament
	err := global2.Sport().Where("id in ?", ids).Delete(&model).Error
	if err != nil {
		global2.Log.Error("删除赛事失败：", err, "ids: ", ids)
		return
	}
}
func GetUniqueTournamentIds(id int) []int {
	var records []int
	model := models_sports.CricketUniqueTournament{}
	global2.Sport().Model(&model).Where("id > ?", id).Limit(120).Pluck("id", &records)
	return records
}
func GetUniqueTournamentIdMaps(ids []int) (map[int]models_sports.CricketUniqueTournament, error) {
	var records []models_sports.CricketUniqueTournament
	data := make(map[int]models_sports.CricketUniqueTournament)

	queryIds := utils.RemoveDuplicatesAndEmpty(ids)
	// 空数据不查询
	if len(queryIds) == 0 {
		return data, nil
	}
	err := global2.Sport().Model(&records).Where("id in ?", queryIds).Find(&records).Error
	if err != nil {
		return nil, err
	}
	for i, record := range records {
		data[record.ID] = records[i]
	}
	return data, nil
}
